package org.example.nio.reactormodel;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;

/**
 * 子反应器，负责事件分发，但是不负责事件处理
 *
 * @author hh
 * @since 2024/10/27
 */
public class SubReactor implements Runnable{

    // 每个线程负责一个选择器的查询和选择
    final Selector selector;

    public SubReactor(Selector selector) {
        this.selector = selector;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                selector.select();
                Set<SelectionKey> keySet = selector.selectedKeys();
                Iterator<SelectionKey> it = keySet.iterator();
                while (it.hasNext()) {
                    // dispatch所查询的事件
                    SelectionKey sk = it.next();
                    dispatch(sk);
                }
                keySet.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    void dispatch(SelectionKey sk) {
        Runnable handler = (Runnable) sk.attachment();
        // 获取之前attach绑定到选择键的handler处理器对象，执行事件处理
        if (handler != null) {
            handler.run();
        }
    }
}
